<?php

/**
 * @filesource Communicates with the Student control file to know which student
 * data to get and set. It is the only file that has the SQL queries and MySQL
 * connections
 *
 * @copyright 2011 by Dan, Steven, Brice, Mike, and Aaron.  This program is part
 * of Internship 2 Career, which is free software. It comes with absolutely no
 * warranty. You can redistribute or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation (For
 * more information, see <http://www.gnu.org/licenses/).
 *
 * @version February 10, 2011
 *
 * @author Steven Simard, Brice Rader and Aaron Jarzombeck
 */
/**
 * Represents student data stored in the dbStudent table.
 */

class dbStudent {


    /**
     * Creates the table corresponding to this database controller.
     * @return true if MySQL server does not report any error. Otherwise,
     * prints out the error and returns false. 
     */
    static function createTable() {
        //Create table stuent
        $query = "
        create table student(
            studentID               int             NOT NULL AUTO_INCREMENT,
            fname                   varchar(25)     NOT NULL,
            lname                   varchar(25)     NOT NULL,
            username                varchar(10)     NOT NULL,
            currentGPA              decimal(4,2)    NOT NULL,
            major                   text            NOT NULL,
            yearStatus              text                NULL,
            graduationYear          varchar(10)         NULL,
            gotHired                varchar(10)         NULL,
            constraint PK_Student PRIMARY KEY (studentID)
);
    ";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }

        //Previous query was successful.
        return true;
    }

    /**
     * Retrieves all the data from table students
     * @return Resource object that contains retrieved data. If query is fails,
     * it returns false.
     */
    function getAllStudents() {

        $query = "SELECT * FROM student";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }

        //Query was successful.
        return $result;
    }

    /**
     * Checks if ID exists.
     * @param Student $s identifies student object
     * @return true if the query is successful.
     */
    function checkStudentID($s) {
        if (!($s instanceof Student)) {
            return false;
        }
        $studentID = $s->getStudentID();
        connectToDatabase();
        if (mysql_num_rows(mysql_query("SELECT * FROM student WHERE
                studentID=$studentID")) == false) {
            mysql_close();
            return false;
        } else {
            return true;
        }
    }

    /**
     * Updates student information.
     * @param Student $s The student to be updated
     * @return true if the query is successful.
     */
    function updateStudent($s) {
        if (!$s instanceof student) {
            echo ("Invalid argument updateStudent($s) function<br />");
            return false;
        }
        $studentID = $s->getStudentID();
        $error = true;

        if ($s->getFName() != '') {
            $error *= mysql_query("UPDATE student SET fname='" . $s->getFName()
                            . "' WHERE studentID=$studentID");
        }
        if ($s->getLName() != '') {
            $error *= mysql_query("UPDATE student SET lname='" . $s->getLName()
                            . "' WHERE studentID=$studentID");
        }
        if ($s->getUsername() != '') {
            $error *= mysql_query("UPDATE student SET username='" .
                            $s->getUsername() . "' WHERE studentID=$studentID");
        }
        if ($s->getCurrentGPA() != '') {
            $error *= mysql_query("UPDATE student SET currentGPA='" .
                            $s->getCurrentGPA() . "' WHERE studentID=
                    $studentID");
        }
        if ($s->getMajor() != '') {
            $error *= mysql_query("UPDATE student SET major='" . $s->getMajor()
                            . "' WHERE studentID=$studentID");
        }
        if ($s->getYearStatus() != '') {
            $error *= mysql_query("UPDATE student SET yearStatus='" .
                            $s->getYearStatus() . "' WHERE studentID=
                            $studentID");
        }
        if ($s->getGraduationYear() != '') {
            $error *= mysql_query("UPDATE student SET graduationYear='" .
                            $s->getGraduationYear() . "' WHERE studentID=
                    $studentID");
        }
        if ($s->getGotHired() != '') {
            $error *= mysql_query("UPDATE student SET gotHired='" .
                            $s->getGotHired() . "' WHERE studentID=$studentID");
        }
        return $error;
    }

    /**
     * Deletes data from the student table.
     * @param student $s The data to be deleted. It has values for all the
     * columns in the table, including primary key value.
     * @return true if the query is successful.
     */
    function deleteStudent($s) {
        if (!$s instanceof student) {
            echo ("Invalid argument deleteStudent($s) function<br />");
            return false;
        }

        //Compose the DELETE FROM query string.
        $query = sprintf("DELETE FROM student WHERE studentID = %d",
                        $s->getStudentID()
        );
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }

        //Query was successful.
        return true;
    }

	/**
	* Gets student IDs
	* @param student $s
	*/
    function getStudentID($s) {
        $result = mysql_query("SELECT stduentID FROM student WHERE
            studentID='$s'");
        $row = mysql_fetch_row($result);
        return $row['0'];
    }

    function getFname($s) {
        $query = "SELECT fname FROM student
        WHERE studentID='$s'";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful.
        return $result;
    }

	/**
	* Gets student last name
	* @param student $s
	* @return last name
	*/
    function getLname($s) {
        $query = "SELECT lname FROM student
        WHERE studentID='$s'";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful.
        return $result;
    }

	/**
	* Gets student username
	* @param student $s
	* @return username
	*/
    function getUsername($s) {
        $query = "SELECT username FROM student
        WHERE studentID='$s'";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful.
        return $result;
    }

	/**
	* Gets current GPA
	* @param $s
	* @return object returns current GPA
	*/
    function getCurrentGPA($s) {
        $query = "SELECT currentGPA FROM student
        WHERE studentID='$s'";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful.
        return $result;
    }

	/**
	* Gets major
	* @param $s
	* @return object returns major
	*/
    function getMajor($s) {
        $query = "SELECT major FROM student
        WHERE studentID='$s'";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful.
        return $result;
    }

	/**
	* Gets year status
	* @param $s
	* @return object returns year status
	*/
    function getYearStatus($s) {
        $query = "SELECT yearStatus FROM student
        WHERE studentID='$s'";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful.
        return $result;
    }

	/**
	* Gets graduation year
	* @param $s
	* @return object returns graduation year
	*/
    function getGraduationYear($s) {
        $query = "SELECT graduationYear FROM student
        WHERE studentID='$s'";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful.
        return $result;
    }

	/**
	* Gets year they were hired
	* @param $s
	* @return object returns year
	*/
    function getGotHired($s) {
        $query = "SELECT gotHired FROM student
        WHERE studentID='$s'";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful.
        return $result;
    }

    /**
     * Adds data from the student table.
     * @param student $s The data to be added. It has values for all the columns
     * in the table, including primary key value.
     * @return true if the query is successful.
     */
    static function addStudent($s, &$id) {

        if (!($s instanceof Student)) {
            echo ("Invalid argument addStudent() function<br />");
            return false;
        }

        //Compose the ADD query string. Primary key value is missing.
        //Database server automatically generates a unique ID for the primary
        //key.
        $query = sprintf("INSERT INTO student VALUES (null, '%s', '%s', '%s', %f,
            '%s', '%s', '%s', '%s')",
                        $s->getFname(),
                        $s->getLname(),
                        $s->getUsername(),
                        $s->getCurrentGPA(),
                        $s->getMajor(),
                        $s->getYearStatus(),
                        $s->getGraduationYear(),
                        $s->getGotHired()
        );
        printf("->Query: %s<br />", $query);
        connectToDatabase();
        $result = mysql_query($query);        
        mysql_close();
        $id = mysql_insert_id();
        printf("->StudentID: %d<br />", $id);
        if ($result == false) {
            echo mysql_error( );
            return false;
        }
        //Query was successful.
        return true;
    }

    /**
     * Gets all the student information for a specified ID.
     * @param int $studentID ID of the student you want to get.
     * @return true if the query is successful.
     */
    function getStudent($studentID) {
        if (!$s instanceof Student) {
            echo ("Invalid argument getStudent($s) function<br />");
            return false;
        }
        $result = mysql_query("SELECT * FROM student WHERE studentID=
                $studentID");
        if (!$result) {
            return false; //studentID does not exist
        } else {
            $row = mysql_fetch_assoc($result);
            $s = new Student();
            $s->setStudentID($studentID);
            $s->setFName($row['fname']);
            $s->setLName($row['lname']);
            $s->setUsername($row['username']);
            $s->setCurrentGPA($row['currentGPA']);
            $s->setMajor($row['major']);
            $s->setYearStatus($row['yearStatus']);
            $s->setGraduationYear($row['graduationYear']);
            $s->setGotHired($row['gotHired']);
            return $s;
        }
    }

    /**
     * Gets the gotHired details of a specified internship.
     * @param getGotHired $val
     * @return object Returns 0 on failure, or a Internship object on success
     */


    public static function getAllByID($id, &$output) {
        $query = sprintf("SELECT fname, lname, username,
            currentGPA, major, yearStatus, graduationYear, gotHired
            FROM student WHERE studentID=%d", $id);
        printf("->Query: %s<br />", $query);
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();

        if ($result == false) {
            $output = sprintf("%s", mysql_error());
            return false;
        }
        //process result and print out warning or attribute values
        return dbStudent::checkForOneInstance($result, $id, $output);
    }

    private static function checkForOneInstance($result, $id, &$output) {
        //Local variables are initialized.
        $errorStatus = false;

        $howMany = mysql_num_rows($result);
        //printf("->Found %d instance(s) for studentID=%d.<br />", $howMany, $id);
        switch ($howMany) {
            case 0:
                $output = sprintf("No Student instance with ID=%d was found.",
                                $id);
                $errorStatus = true;
                break;
            case 1:
                //mysql_fetch() DOES NOT return primary key values
                $output = mysql_fetch_assoc($result);
                $errorStatus = false;
                break;
            default:
                $output = sprintf("There are multiple Student instances with
                                  ID=%d.", $id);
                $errorStatus = true;
                break;
        }
        return $errorStatus;
    }

}

?>
